//
//  UIImage+Compress.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/26.
//

#import "UIImage+Compress.h"

@implementation UIImage (Compress)

- (NSData *)compressToMaxFileSizeKB:(NSInteger)maxFileSizeKB {
    // 1. 先缩放图片（减少像素，但不裁剪）
    UIImage *resizedImage = [self resizeImageToMaxDimension:1024]; // 限制最长边 1024px
    
    // 2. 循环调整压缩质量，直到满足大小
    CGFloat compression = 1.0;
    NSData *imageData = UIImageJPEGRepresentation(resizedImage, compression);
    
    while (imageData.length > maxFileSizeKB * 1024 && compression > 0.1) {
        compression -= 0.05; // 每次降低 5% 质量
        imageData = UIImageJPEGRepresentation(resizedImage, compression);
    }
    
    // 3. 如果仍然太大，进一步缩放尺寸
    if (imageData.length > maxFileSizeKB * 1024) {
        resizedImage = [self resizeImageToMaxDimension:512]; // 进一步缩放
        imageData = UIImageJPEGRepresentation(resizedImage, 0.8); // 重新压缩
    }
    
    return imageData;
}
 
/**
 * 调整图片尺寸（保持宽高比，不裁剪）
 * @param maxDimension 最大边长（像素）
 * @return 缩放后的 UIImage
 */
- (UIImage *)resizeImageToMaxDimension:(CGFloat)maxDimension {
    CGSize originalSize = self.size;
    if (originalSize.width <= maxDimension && originalSize.height <= maxDimension) {
        return self; // 无需缩放
    }
    
    CGFloat scale = maxDimension / MAX(originalSize.width, originalSize.height);
    CGSize newSize = CGSizeMake(originalSize.width * scale, originalSize.height * scale);
    
    UIGraphicsBeginImageContext(newSize);
    [self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resizedImage;
}

@end
